package com.joysuch.wwyt.workflow.controller;


import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.exception.ApiCoreException;
import com.joysuch.wwyt.repeatsubmit.NoRepeatSubmit;
import com.joysuch.wwyt.workflow.bean.*;
import com.joysuch.wwyt.workflow.bean.vo.RelatedTaskInfoVO;
import com.joysuch.wwyt.workflow.entity.WorkFlowTask;
import com.joysuch.wwyt.workflow.entity.WorkFlowTaskHistory;
import com.joysuch.wwyt.workflow.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/workflow-task")
@Api(tags = "业务流程-任务节点管理")
@CrossOrigin
public class WorkFlowTaskController {

    @Autowired
    private WorkFlowTaskService workFlowTaskService;
    @Autowired
    private WorkFlowTaskProcessListService workFlowTaskProcessListService;
    @Autowired
    private WorkFlowTaskHistoryService workFlowTaskHistoryService;
    @Autowired
    private WorkFlowTaskSignService workFlowTaskSignService;
    @Autowired
    private WorkFlowTaskDynamicService workFlowTaskDynamicService;

    @PostMapping("/submitTask")
    @ApiOperation(value = "提交当前任务节点")
    @NoRepeatSubmit(paramNames = "workFlowProcessId,taskCode")
    public ResultBean submitTask(@RequestBody WorkFlowExecuteTaskBean taskBean, HttpServletRequest request) {
        try {
            return workFlowTaskService.submitTask(taskBean, request);
        } catch (ApiCoreException ae) {
            return ResultBean.fail(ae.getCode(), ae.getMessage());
        } catch (Exception e) {
            log.error("任务节点提交失败", e);
            throw new ActivitiException("任务节点提交失败", e);
        }
    }


    /*@PostMapping("/tasklist")
    @ApiOperation(value = "任务列表", response = WorkFlowTaskListBean.class)
    public ResultBean tasklist(@RequestBody WorkFlowTaskQueryBean queryBean) {
        try {
            Pageable pageable = QPageRequest.of(queryBean.getPage(), queryBean.getSize());
            return workFlowTaskService.findTaskList(queryBean, pageable);
        } catch (Exception e) {
            log.error("获取任务列表失败", e);
            throw new ActivitiException("获取任务列表失败", e);
        }

    }*/


    @GetMapping("/editTask/{id}")
    @ApiOperation(value = "编辑任务节点", response = WorkFlowTaskListBean.class)
    @ApiImplicitParam(name = "id", value = "主键ID", paramType = "path", required = true)
    public ResultBean editTask(@PathVariable Long id) {
        return workFlowTaskService.getTaskById(id);
    }


    @GetMapping("/relatedTask/{taskCode}")
    @ApiOperation(value = "获取关联任务详情", response = RelatedTaskInfoVO.class)
    @ApiImplicitParam(name = "taskCode", value = "任务编号", paramType = "path", required = true)
    public ResultBean editTask(@PathVariable String taskCode) {
        try {
            RelatedTaskInfoVO relatedTaskInfoVO = workFlowTaskService.getRelatedTaskByCode(taskCode);
            return ResultBean.success(relatedTaskInfoVO);
        } catch (ApiBusinessException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
    }

    @PostMapping("/saveTask")
    @ApiOperation(value = "保存任务节点", response = WorkFlowExecuteTaskBean.class)
    @ApiImplicitParam(name = "id", value = "主键ID", paramType = "path", required = true)
    @NoRepeatSubmit(paramNames = "workFlowProcessId")
    public ResultBean saveTask(@RequestBody WorkFlowExecuteTaskBean taskBean) {
        try {
            Long id = workFlowTaskService.saveTask(taskBean,true);
            return ResultBean.success(id);
        } catch (ApiBusinessException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        } catch (IOException e) {
            log.error("保存任务节点失败", e);
            return ResultBean.fail(Status.SAVE_TASK_ERROR);
        }
    }

    @PostMapping("/tempSaveTask")
    @ApiOperation(value = "暂存", response = WorkFlowExecuteTaskBean.class)
    @ApiImplicitParam(name = "id", value = "主键ID", paramType = "path", required = true)
    @NoRepeatSubmit(paramNames = "workFlowProcessId")
    public ResultBean tempSaveTask(@RequestBody WorkFlowExecuteTaskBean taskBean) {
        try {
            Long id = workFlowTaskService.tempSaveTask(taskBean);
            return ResultBean.success(id);
        } catch (ApiBusinessException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        } catch (IOException e) {
            log.error("暂存任务节点失败", e);
            return ResultBean.fail(Status.SAVE_TASK_ERROR);
        }
    }

    @GetMapping("/deleteTask/{id}")
    @ApiImplicitParam(name = "id", value = "主键ID", paramType = "path", required = true)
    @ApiOperation(value = "删除任务节点")
    public ResultBean deleteTask(@PathVariable Long id, Integer flag, String comments) {
        try {
            workFlowTaskService.deleteTask(id, flag, comments);
        } catch (ApiCoreException e) {
            log.error(e.getMessage(), e);
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
        return ResultBean.defaultSuccessResult();
    }


    @PostMapping("/createNewTask")
    @ApiOperation(value = "创建业务流程新任务--其他业务跳转流程引擎入口")
    @NoRepeatSubmit(paramNames = "workFlowId")
    public ResultBean createNewTask(@RequestBody WorkFlowTaskCreateBean bean, HttpServletRequest request) {
        String taskId = null;
        try {
            taskId = workFlowTaskService.createNewTask(bean, request);
        } catch (ApiBusinessException e) {
            log.error(e.getMessage(), e);
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
        return ResultBean.success(taskId);
    }

    @PostMapping("/pageHistory")
    @ApiOperation(value = "获取历史列表(分页）", response = WorkFlowTaskHistoryBean.class)
    public ResultBean page(@RequestBody WorkFlowTaskHistoryQueryBean bean) {
        Pageable pageable = QPageRequest.of(bean.getPage(), bean.getSize());
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        Page<WorkFlowTaskHistoryBean> list = workFlowTaskHistoryService.pageList(bean, pageable);
        return ResultBean.pageData(list);
    }

    @GetMapping("/getHistoryById/{id}")
    @ApiImplicitParam(name = "id", value = "主键ID", paramType = "path", required = true)
    @ApiOperation(value = "根据ID获取历史记录详情")
    public ResultBean getHistoryById(@PathVariable Long id) {
        WorkFlowTaskHistory flowTaskHistory = workFlowTaskHistoryService.findById(id);
        return ResultBean.success(flowTaskHistory);
    }

    @GetMapping("workFlow-task-history")
    @ApiOperation(value = "流程任务历史", response = WorkFlowTaskHistory.class)
    public ResultBean workFlowTaskHis(@RequestParam("taskId") Long taskId) {
        return workFlowTaskHistoryService.workFlowTaskHis(taskId);
    }

    @GetMapping("assign-history")
    @ApiOperation(value = "流程任务审批历史", response = WorkFlowTaskHistory.class)
    public ResultBean workFlowTaskAssignHis(@RequestParam("taskCode") String taskCode) {
        return workFlowTaskHistoryService.workFlowTaskAssignHis(taskCode);
    }

    @GetMapping("taskList/vue-type")
    @ApiOperation(value = "获取某个业务类型下的所有业务数据", response = WorkFlowTask.class)
    public ResultBean taskListVueType(String type, Pageable pageable) {
        return workFlowTaskService.taskListVueType(type, pageable);
    }

    @PostMapping("/process-list")
    @ApiOperation(value = "待办任务列表")
    public ResultBean findProcessList(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        return workFlowTaskProcessListService.findProcessList(queryBean);
    }

    @RequiresPermissions("workflow:menu:allTaskList")
    @PostMapping("/all-task-list")
    @ApiOperation(value = "所有任务列表")
    public ResultBean findAllTaskList(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        return workFlowTaskProcessListService.findAllTaskList(queryBean);
    }

    @RequiresPermissions("workflow:menu:allTaskList")
    @PostMapping("/all-task-new-list")
    @ApiOperation(value = "所有任务列表")
    public ResultBean findAllTaskNewList(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        return workFlowTaskProcessListService.findAllTaskNewList(queryBean);
    }


    @PostMapping("/export")
    @ApiOperation(value = "流程导出")
    public ResultBean export(@RequestBody WorkFlowProcessTaskQueryBean queryBean, HttpServletResponse response) {
        try {
            workFlowTaskProcessListService.export(queryBean, response);
        } catch (IOException e) {
            return ResultBean.fail(Status.EXPORT_PROCESS_DATA_ERROR);
        }
        return ResultBean.defaultSuccessResult();
    }

    @PostMapping("/check-export-data")
    @ApiOperation(value = "流程导出")
    public ResultBean checkExportData(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        try {
            return ResultBean.success(workFlowTaskProcessListService.checkExportData(queryBean));
        } catch (ApiCoreException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
    }

    @PostMapping("/process-stat")
    @ApiOperation(value = "待办任务统计")
    public ResultBean findProcessStat(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        return ResultBean.success(workFlowTaskProcessListService.findProcessStat(queryBean));
    }

    @PostMapping("/verify-sign-area")
    @ApiOperation(value = "签字位置校验")
    public ResultBean verifySignArea(@Valid @RequestBody WorkFlowSignBean signBean) {
        try {
            return ResultBean.success(workFlowTaskSignService.verifySignArea(signBean));
        } catch (ApiCoreException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
    }

    @PostMapping("/verify-sign-area-bluetooth")
    @ApiOperation(value = "签字位置校验-蓝牙")
    public ResultBean verifySignAreaBluetooth(@RequestBody WorkFlowSignBean signBean) {
        return ResultBean.success(workFlowTaskSignService.verifySignAreaBluetooth(signBean));
    }

    @GetMapping("/open-service-token")
    @ApiOperation(value = "开放平台token获取")
    public ResultBean getOpenServiceToken() {
        try {
            return ResultBean.success(workFlowTaskSignService.getOpenServiceToken());
        } catch (ApiCoreException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
    }

    @PostMapping("/summary-inquiry-list")
    @ApiOperation(value = "汇总查新列表")
    public ResultBean findAllTaskList(@RequestBody SummaryInquiryQueryBean queryBean) {
        return workFlowTaskProcessListService.findSummaryInquiryTaskList(queryBean);
    }

    @PostMapping("/task-simple-list")
    @ApiOperation(value = "关联其它作业列表")
    public ResultBean findTaskSimpleList(@RequestBody WorkFlowProcessTaskQueryBean queryBean) {
        try {
            return workFlowTaskProcessListService.findTaskSimpleList(queryBean);
        } catch (ApiCoreException e) {
            return ResultBean.fail(e.getCode(), e.getMessage());
        }
    }

    @GetMapping("getSignatureByTaskCode")
    @ApiOperation(value = "获取签字位置详情")
    public ResultBean getSignatureByTaskCode(String taskCode) {
        List<LocationVerifyRecordBean> list = workFlowTaskSignService.getLocationVerifyRecordByTaskCode(taskCode);
        return ResultBean.success(list);
    }

    @GetMapping("/getProcessTimePeriod")
    @ApiOperation(value = "获取任务的时间段")
    public ResultBean getProcessTimePeriod(WorkFlowSubmitTimeBean bean){
        return workFlowTaskHistoryService.getProcessTimePeriod(bean) == null ? ResultBean.defaultSuccessResult() : ResultBean.success(workFlowTaskHistoryService.getProcessTimePeriod(bean));
    }

    @GetMapping("/deleteTest")
    @ApiOperation(value = "deleteTest")
    public ResultBean deleteTest(String code){
        workFlowTaskDynamicService.batchDeletaDynamicRecordsByTaskCode(code);
         return ResultBean.success("");
    }

    @GetMapping("/redisTest")
    @ApiOperation(value = "redisTest")
    public ResultBean deleteTest(){
        workFlowTaskService.processDynamicRecords();
        return ResultBean.success("");
    }
}
